using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    private Transform birdTransform;
    private readonly float smoothTime = 0.4f; // 跟随平滑时间
    private readonly float leftLimit = -2f;   // 左侧最大限制
    private readonly float rightLimit = 25f;  // 右侧最大限制
    private Vector3 velocity = Vector3.zero;
    private float initialY;
    private Transform piggieTransform;
    private bool canFollowBird = false;
    private void Start()
    {
        piggieTransform = GameObject.FindGameObjectWithTag("Emeny").transform;
        // 保存摄像机初始高度
        initialY = transform.position.y;

        birdTransform = GameObject.FindGameObjectWithTag("Player").transform;

        transform.position = new Vector3(piggieTransform.position.x, initialY, transform.position.z);
        Invoke(nameof(FollowTarget), 2f);
    }

    private void LateUpdate()
    {
        if (canFollowBird)
        {
            FollowTarget();
        }
    }
    private void FollowTarget()
    {
        canFollowBird = true;
        if (birdTransform != null)
        {
            // 计算目标位置（限制在左右边界之间）
            float clampedX = Mathf.Clamp(
                birdTransform.position.x,
                leftLimit,
                rightLimit
            );
            // 计算目标位置
            Vector3 targetPosition = new(
                clampedX, // 限制两侧
                initialY,
                transform.position.z
            );
            // 平滑移动
            transform.position = Vector3.SmoothDamp(
                transform.position,
                targetPosition,
                ref velocity,
                smoothTime
            );
        }
        else
        {
            if (GameManager.instance.HasEnoughShots())
            {
                birdTransform = GameObject.FindGameObjectWithTag("Player").transform;
            }
            else
            {
                canFollowBird = false;
            }
        }
    }
}